const memberinfo_collection = db.collection("memberinfo");
(function() {
	var _con = function(info) {
		var self = this;
		if(info){
			self.info = info;
		}
	}

	module.exports = _con;

	_con.prototype.save = co.wrap(function*(data) {
        printData("正在创建保存用户信息", data);
        var self = this;
        var _mid = "m_" + Math.random().toString(16).substr(2, 4) + (new Date()).getTime().toString(16);
        var insert_data = {_id:_mid};
        //判断用户是否登录
       	if(typeof self.info !='object' || !self.info._id){
        	return printError('请先登录！');
        } 
        var user_collection = db.collection('user');
        var user_data = yield mongo.findOneByObjectId(user_collection,self.info._id);
        if(!user_data){
			return printError('用户不存在！');
        }
        var arr_type = [1,2,3];
        var arr_type_msg = ['普通用户','白金会员','钻石会员','至尊会员']
        if(user_data.type>=data.type){
        	return printError('您已经是'+arr_type_msg[user_data.type]+'了，不能申请了！');
        }
        var memberinfo = yield mongo.findOne(memberinfo_collection,{query:{uid:self.info._id,status:1}});
        if(memberinfo){
        	return printError('您已经申请会员了，请审核通过后再申请！');
        }
        insert_data.uid = self.info._id;
        if(!data.realname){
        	return printError('真实名字不能为空！');
        }
        insert_data.realname = data.realname;
        if(!data.type){
        	return printError('会员类型不能为空！');
        }
        var bool = false;
        for(var i=0;i<arr_type.length;i++){
        	if(data.type==arr_type[i]){
        		bool = true;
        		break;
        	}
        }
        if(!bool){
        	return printError('会员类型不存在！');
        }
        insert_data.type = data.type;
        if(!data.idcard||typeof data.idcard!='string'||data.idcard.length!=18){
            return printError('身份证号码不正确！');
        }
        var user_collection = db.collection('user');
        var arr_data = yield mongo.findOne(user_collection,{query:{idcard:data.idcard,_id:{$ne:self.info._id}}});
        if(arr_data){
            return printError('身份证号码已经被注册！');
        }
        insert_data.idcard = data.idcard;
        insert_data.gender = data.gender=='女'?'女':'男';
        if(!data.job){
        	return printError('职务不能为空！');
        }
        insert_data.job = data.job;

		//审核状态
		insert_data.status  = 1;
        // 创建时间
        insert_data.createtime = (new Date()).getTime();
        // 自有id,u_+2位随机数+当前时间的毫秒数转16进制 
        return yield mongo.insertOne(memberinfo_collection, insert_data);
    });

    _con.prototype.count = co.wrap(function*(data) {
        var self = this;
        var status = parseInt(data.status);
        var params = {query:{}};
        if(status.length>0){
            params.query.status = status;
        }
        return yield mongo.count(memberinfo_collection,params);
    });
}());